const fs = require('fs');

function dealWithSubRegion(code, latLon) {
  const output = [];
  for(let i = 0; i < code.length; i++) {
    for(let j = 0; j < latLon.length; j++) {
      if(code[i].name == latLon[j].name) {
        output.push({
          name: code[i].name,
          shortName: code[i].shortName,
          code: code[i].code,
          lat: latLon[j].lat,
          lon: latLon[j].lon,
          layer: 2
        });
      }
    } 
  }
  return output; 
}

fs.readFile('./region_code.json', 'utf8', function(err1, data1) {
  fs.readFile('./region_lat_lon.json', 'utf8', function(err2, data2) {
    const regionCode = JSON.parse(data1).regionCode;
    const regionLatLon = JSON.parse(data2).regionCode;
    const output = [];
    for(let i = 0; i < regionCode.length; i++) {
      for(let j = 0; j < regionLatLon.length; j++) {
        if(regionCode[i].name === regionLatLon[j].name) {
          output.push({
            name: regionCode[i].name,
            shortName: regionCode[i].shortName,
            code: regionCode[i].code,
            lat: regionLatLon[j].lat,
            lon: regionLatLon[j].lon,
            layer: 1,
            subRegion: dealWithSubRegion(regionCode[i].subRegion, regionLatLon[j].subRegion)
          });
        }
      }
    }
    // console.log(output);
    fs.writeFile('./deal_with_data.json', JSON.stringify(output), 'utf8', function(err) {
      console.log(err);      
    });
  });
});